<template>
  <el-config-provider :locale="zhCn">
  <div class="page">
    <div class="toolbar">
      <el-form :inline="true" :model="filters" class="filters">
        <el-form-item label="事件名称">
          <el-input v-model="filters.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="事件类型">
          <el-select v-model="filters.event_type_id" placeholder="请选择" clearable style="min-width:200px">
            <el-option v-for="t in eventTypes" :key="t.code" :label="t.name" :value="t.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联活动">
          <el-select v-model="filters.activity_id" placeholder="请选择活动" clearable style="min-width:240px">
            <el-option 
              v-for="activity in activityOptions" 
              :key="activity.id" 
              :label="activity.name" 
              :value="activity.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="min-width:140px">
            <el-option label="新建" value="new" />
            <el-option label="跟进中" value="in_progress" />
            <el-option label="已解决" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker 
            v-model="filters.timeRange" 
            type="daterange" 
            start-placeholder="开始" 
            end-placeholder="结束" 
            value-format="YYYY-MM-DD" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reload">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="actions">
        <el-button type="primary" @click="openCreate">新建事件</el-button>
        <el-button @click="backToActivities">返回活动</el-button>
      </div>
    </div>
    <div class="table-area">
      <div class="table-container">
        <el-table :data="items" style="width:100%" max-height="100%">
          <el-table-column prop="name" label="事件名称" min-width="160" />
          <el-table-column label="事件类型" min-width="160">
            <template #default="{ row }">{{ idToName[row.event_type_id] || row.event_type_id }}</template>
          </el-table-column>
          <el-table-column label="关联活动" min-width="200">
            <template #default="{ row }">{{ getActivityName(row.activity_id) }}</template>
          </el-table-column>
          <el-table-column prop="occurred_at" label="发生时间" min-width="180" />
          <el-table-column prop="location_admin" label="行政区划" min-width="140" />
          <el-table-column prop="location_detail" label="详细地点" min-width="180" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="240" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" width="300">
            <template #default="{ row }">
              <el-button @click="openEdit(row)">修改</el-button>
              <el-popconfirm title="确定删除该事件？" @confirm="remove(row)">
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper, total"
            :total="total"
            :page-size="pageSize"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            @size-change="onSizeChange"
            @current-change="onPageChange"
          />
        </el-config-provider>
      </div>
    </div>

    <el-dialog v-model="showDialog" :title="dialogTitle" width="640px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="事件名称" prop="name"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="事件类型" prop="event_type_id">
          <el-select v-model="form.event_type_id" placeholder="请选择事件类型" style="min-width:240px">
            <el-option v-for="t in eventTypes" :key="t.code" :label="t.name" :value="t.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联活动" prop="activity_id">
          <el-select v-model="form.activity_id" placeholder="请选择关联活动" style="min-width:240px">
            <el-option 
              v-for="activity in activityOptions" 
              :key="activity.id" 
              :label="activity.name" 
              :value="activity.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="occurred_at">
          <el-date-picker 
            v-model="form.occurred_at" 
            type="datetime" 
            value-format="YYYY-MM-DDTHH:mm:ss"
            placeholder="选择事件发生时间"
          />
        </el-form-item>
        <el-form-item label="行政区划" prop="location_admin">
          <el-cascader 
            v-model="formRegionCodes" 
            :options="regionOptions" 
            placeholder="请选择省/市/区" 
            clearable 
            @change="onRegionFormChange" 
          />
        </el-form-item>
        <el-form-item label="详细地点" prop="location_detail"><el-input v-model="form.location_detail" /></el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="min-width:140px">
            <el-option label="新建" value="new" />
            <el-option label="跟进中" value="in_progress" />
            <el-option label="已解决" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { api } from '../../api/client'
import { regionData } from 'element-china-area-data'
import { nextTick } from 'vue'

type Event = {
  id: string
  activity_id: string
  event_type_id: string
  name: string
  occurred_at: string
  location_admin: string
  location_detail: string
  latitude?: number | null
  longitude?: number | null
  description: string
  status: string
  created_by?: string | null
  created_at?: string | null
  updated_by?: string | null
  updated_at?: string | null
}

type DictItem = { id: string; code: string; name: string }

type ActivityOption = {
  id: string
  name: string
}

const items = ref<Event[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const eventTypes = ref<DictItem[]>([])
const codeToId = ref<Record<string, string>>({})
const idToCode = ref<Record<string, string>>({})
const idToName = ref<Record<string, string>>({})
const regionOptions = regionData as any

const activityOptions = ref<ActivityOption[]>([])

const filters = reactive({
  name: '',
  event_type_id: '',
  activity_id: '',
  location_admin: '',
  regionCodes: [] as string[],
  status: '',
  timeRange: [] as string[]
})

function resetFilters() {
  filters.name = ''
  filters.event_type_id = ''
  filters.activity_id = ''
  filters.location_admin = ''
  filters.status = ''
  filters.timeRange = []
}

function labelsFromCodes(codes: string[]): string {
  const labels: string[] = []
  let nodes: any[] = regionOptions as any[]
  (codes || []).forEach((code) => {
    const n = nodes?.find((x: any) => x.value === code || x.code === code)
    if (n) {
      labels.push(n.label || n.name)
      nodes = n.children || []
    }
  })
  return labels.join(' / ')
}

function onRegionFilterChange(codes: string[]) {
  filters.regionCodes = codes || []
  filters.location_admin = labelsFromCodes(codes || [])
}

function getStatusType(status: string): string {
  switch (status) {
    case 'new': return 'info'
    case 'in_progress': return 'warning'
    case 'resolved': return 'success'
    case 'closed': return 'info'
    default: return 'info'
  }
}

function getStatusText(status: string): string {
  switch (status) {
    case 'new': return '新建'
    case 'in_progress': return '跟进中'
    case 'resolved': return '已解决'
    case 'closed': return '已关闭'
    default: return status
  }
}

function getActivityName(activityId: string): string {
  const activity = activityOptions.value.find(a => a.id === activityId)
  return activity ? activity.name : activityId
}

async function load() {
  const params: any = { page: page.value, page_size: pageSize.value }
  if (filters.name) params.name = filters.name
  if (filters.event_type_id) params.event_type_id = codeToId.value[filters.event_type_id] || filters.event_type_id
  if (filters.activity_id) params.activity_id = filters.activity_id
  if (filters.location_admin) params.location_admin = filters.location_admin
  if (filters.status) params.status = filters.status
  if (filters.timeRange && filters.timeRange.length === 2) {
    params.time_start = filters.timeRange[0]
    params.time_end = filters.timeRange[1]
  }
  const res = await api.get('/events', { params })
  const data = res.data
  items.value = Array.isArray(data.items) ? data.items : Array.isArray(data) ? data : []
  total.value = typeof data.total === 'number' ? data.total : typeof data.total_count === 'number' ? data.total_count : Number(res.headers['x-total-count'] ?? items.value.length)
}

async function loadEventTypes() {
  const { data } = await api.get('/dictionaries/items', { params: { type_code: 'event_type', page_size: 200 } })
  eventTypes.value = data
  const c2i: Record<string, string> = {}
  const i2c: Record<string, string> = {}
  const i2n: Record<string, string> = {}
  data.forEach((d: DictItem) => { c2i[d.code] = d.id; i2c[d.id] = d.code; i2n[d.id] = d.name })
  codeToId.value = c2i
  idToCode.value = i2c
  idToName.value = i2n
}

async function loadActivities() {
  const { data } = await api.get('/activities', { params: { page_size: 1000 } })
  activityOptions.value = Array.isArray(data.items) ? data.items : Array.isArray(data) ? data : []
}

function reload() {
  page.value = 1
  load()
}

function onPageChange(p: number) {
  page.value = p
  load()
}

function onSizeChange(s: number) {
  pageSize.value = s
  page.value = 1
  load()
}

const showDialog = ref(false)
const dialogTitle = ref('新建事件')
const saving = ref(false)
const editingId = ref<string | null>(null)
const formRef = ref()

const form = reactive<Event>({
  id: '',
  activity_id: '',
  event_type_id: '',
  name: '',
  occurred_at: '',
  location_admin: '',
  location_detail: '',
  latitude: null,
  longitude: null,
  description: '',
  status: 'new',
})

const formRegionCodes = ref<string[]>([])
function onRegionFormChange(codes: string[]) {
  formRegionCodes.value = codes || []
  form.location_admin = labelsFromCodes(codes || [])
}

const rules = {
  name: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  event_type_id: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  activity_id: [{ required: true, message: '请选择关联活动', trigger: 'change' }],
  occurred_at: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  location_admin: [{ required: true, message: '请选择行政区划', trigger: 'change' }],
  location_detail: [{ required: true, message: '请输入详细地点', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入事件描述', trigger: 'blur' }],
}

function openCreate() {
  dialogTitle.value = '新建事件'
  editingId.value = null
  Object.assign(form, {
    id: '',
    activity_id: '',
    event_type_id: '',
    name: '',
    occurred_at: '',
    location_admin: '',
    location_detail: '',
    latitude: null,
    longitude: null,
    description: '',
    status: 'new',
  })
  showDialog.value = true
}

function openEdit(row: Event) {
  dialogTitle.value = '修改事件'
  editingId.value = row.id
  Object.assign(form, row)
  form.event_type_id = idToCode.value[row.event_type_id] || ''
  showDialog.value = true
}

async function submit() {
  if (formRef.value) {
    const ok = await new Promise<boolean>((resolve) => formRef.value.validate((v: boolean) => resolve(v)))
    if (!ok) return
  }
  saving.value = true
  const payload: any = { ...form }
  if (payload.event_type_id) {
    const code = payload.event_type_id
    payload.event_type_id = codeToId.value[code] || code
  }
  if (!payload.occurred_at) delete payload.occurred_at
  try {
    if (editingId.value) {
      await api.put(`/events/${editingId.value}`, payload)
    } else {
      await api.post('/events', payload)
    }
    showDialog.value = false
    await load()
  } finally {
    saving.value = false
  }
}

async function remove(row: Event) {
  await api.delete(`/events/${row.id}`)
  await load()
}

onMounted(async () => {
  await Promise.all([loadEventTypes(), loadActivities(), load()])
})

const router = useRouter()
function backToActivities() {
  router.push({ path: '/admin/activities' })
}
</script>

<style scoped>
/* 页面根容器：确保占满整个父容器高度 */
.page { 
  height: 100%; 
  display: flex; 
  flex-direction: column; 
  box-sizing: border-box;
  overflow: hidden;
}

/* 工具栏：固定高度，不伸缩 */
.toolbar { 
  flex-shrink: 0; 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  gap: 12px; 
  padding-bottom: 16px; 
  box-sizing: border-box;
}

.filters { flex: 1; }
.actions { flex-shrink: 0; }

/* 表格区域：占据剩余所有空间 */
.table-area { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  min-height: 0;
  overflow: hidden;
}

/* 表格容器：精确控制高度，确保分页固定在底部 */
.table-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}

/* Element Plus表格深度样式覆盖 */
.table-container :deep(.el-table) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.table-container :deep(.el-table__inner-wrapper) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}

/* 表格头部：固定高度 */
.table-container :deep(.el-table__header-wrapper) {
  flex-shrink: 0;
  height: auto !important;
}

/* 表格主体：占据剩余空间，内部滚动 */
.table-container :deep(.el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto !important;
  height: auto !important;
  min-height: 200px; /* 确保最少显示几行数据 */
}

/* 空数据状态 */
.table-container :deep(.el-table__empty-block) {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 分页：固定在底部 */
.pagination { 
  flex-shrink: 0; 
  display: flex; 
  justify-content: flex-end; 
  padding-top: 16px; 
  padding-bottom: 8px;
  box-sizing: border-box;
  background: white;
  border-top: 1px solid #f0f0f0;
  margin-top: auto; /* 确保固定在底部 */
}

/* 响应式优化 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filters {
    margin-bottom: 12px;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>
